package main

import (
	"flag"
	"fmt"
	"log/slog"
	"os"

	"gitee.com/jiebaiyou/demo-grpc/gateway/internal/app"
	"gitee.com/jiebaiyou/demo-grpc/gateway/services/auth"
	"gitee.com/jiebaiyou/demo-grpc/gateway/services/user"
	"gitee.com/jiebaiyou/demo-grpc/shared/registry"
	"github.com/gin-gonic/gin"
	clientv3 "go.etcd.io/etcd/client/v3"
	"google.golang.org/grpc/resolver"
)

var commit = "none"

func main() {
	slog.Info("版本信息", slog.String("commit", commit))

	// 定义命令行参数, 默认加载开发配置文件dev.yaml
	app.ConfigFile = flag.String("config", "config/yaml/dev.yaml", "path to config file")
	// 解析命令行参数
	flag.Parse()

	// 初始化全局配置
	_, err := app.InitConfig(*app.ConfigFile)
	if err != nil {
		slog.Error("初始化配置文件失败", slog.String("error", err.Error()))
		os.Exit(1)
	}

	err = app.InitLogger()
	if err != nil {
		slog.Error("初始化日志记录器失败", slog.String("error", err.Error()))
		os.Exit(1)
	}

	// 创建ETCD客户端
	etcdClient, err := clientv3.New(clientv3.Config{
		Endpoints: app.Config.ETCD.ENDPOINTS,
		Username:  app.Config.ETCD.USERNAME,
		Password:  app.Config.ETCD.PASSWORD,
	})
	if err != nil {
		slog.Error("创建ETCD客户端失败", slog.String("error", err.Error()))
		os.Exit(1)
	}
	defer etcdClient.Close()

	// 创建服务发现器
	serviceDiscover := registry.NewResolverBuilder(etcdClient)
	resolver.Register(serviceDiscover)

	// 创建auth服务客户端
	dns := fmt.Sprintf("%s:///%s", registry.ServiceDNS, "auth")
	authClient := auth.NewClient(dns)

	// 创建user服务客户端
	dns = fmt.Sprintf("%s:///%s", registry.ServiceDNS, "user")
	userClient := user.NewClient(dns)

	r := gin.Default()

	// 注册auth服务路由
	auth.RegisterRoutes(r, authClient)
	// 注册user服务路由
	user.RegisterRoutes(r, userClient)

	if err := r.Run(":5000"); err != nil {
		slog.Error("启动服务器失败", slog.String("error", err.Error()))
		os.Exit(1)
	}
}
